import os

from django.core.mail import send_mail
from django.db.models import Q
from django.http import JsonResponse

from Friend.models import Friend
from User.models import User


def register(request):
    __mail = request.POST.get("mail")
    __password = request.POST.get("password")
    if User.objects.filter(mail=__mail).count() > 0:
        return JsonResponse({'msg': '账号已存在'})
    User.objects.create(
        mail=__mail,
        password=__password,
        iconUrl="files/defaultaccount.png"
    ).save()
    if User.objects.filter(mail=__mail).count() > 0:
        return JsonResponse({'msg': '注册成功'})
    else:
        return JsonResponse({'msg': '注册失败'})


def login(request):
    __mail = request.POST.get("mail")
    __password = request.POST.get("password")
    us = User.objects.filter(mail=__mail)
    if us.count() > 0:
        u = us.first()
        if u.password == __password:
            return JsonResponse({"msg": "登录成功"})
        else:
            return JsonResponse({"msg": "账号或密码不正确"})
    else:
        return JsonResponse({"msg": "用户不存在"})


def getuserbymail(request):
    __mail = request.POST.get("mail")
    us = User.objects.filter(mail=__mail)
    if us.count() > 0:
        u = us.first()
        return JsonResponse({"msg": "获取成功", "data": {
            "mail": u.mail,
            "password": u.password,
            "nickname": u.nickname,
            "iconUrl": u.iconUrl,
        }})
    else:
        return JsonResponse({"msg": "用户不存在"})


def uploadIconByEmail(request):
    u = User.objects.filter(mail=request.GET.get("mail"))
    if u.count() > 0:
        iconFile = request.FILES.get('file', None)
        if not iconFile:
            return JsonResponse({"msg": "没有上传图片"})
        filename = request.GET.get("mail") + "@icon.png"
        destination = open(os.path.join("files/icon", filename), "wb+")
        for chunk in iconFile.chunks():
            destination.write(chunk)
        destination.close()
        u.update(iconUrl="files/icon/" + filename)
        return JsonResponse({"msg": "修改头像成功"})
    else:
        return JsonResponse({"msg": "用户不存在，修改头像失败"})


def changeNickname(request):
    u = User.objects.filter(mail=request.POST.get("mail"))
    if u.count() > 0:
        u.update(nickname=request.POST.get("nickname"))
        return JsonResponse({"msg": "修改昵称成功"})
    else:
        return JsonResponse({"msg": "用户不存在，修改昵称失败"})


def search(request):
    if request.POST.get("type") == "user":
        u = User.objects.filter(
            Q(nickname__icontains=request.POST.get('kw')) | Q(mail__icontains=request.POST.get('kw')))
        return JsonResponse({"data": [{
            'nickname': each.nickname,
            'iconUrl': each.iconUrl,
            'mail': each.mail
        } for each in u.order_by('-createTime')],
            "msg": "获取成功"})
    else:
        return JsonResponse({"msg": "请传入类型"})


def sendEmail(request):
    send_mail(
        'Talking验证码',
        '您的Talking验证码是:' + request.POST.get('yzm'),
        'timi_xyt@163.com',
        [request.POST.get('mail')],
        fail_silently=False,
    )
    return JsonResponse({"msg": "已发送邮箱"})


def changePasswordByMail(request):
    u = User.objects.filter(mail=request.POST.get("mail"))
    if u.count() > 0:
        u.update(password=request.POST.get("password"), iconUrl=u.iconUrl, nickname=u.nickname)
        return JsonResponse({"msg": "修改成功"})
    else:
        return JsonResponse({"msg": "用户不存在"})


def getPerson(request):  # not myself
    u = User.objects.filter(mail=request.POST.get("other_mail"))
    if u.count() > 0:
        __me_mail = request.POST.get("me_mail")
        __other_mail = request.POST.get("other_mail")
        f = Friend.objects.filter(mail=__me_mail, friendMail=__other_mail)
        isFriend = False
        remark = ""
        if f.count() > 0:
            isFriend = True
            friend = f.first()
            remark = friend.remark
        else:
            isFriend = False
        user = u.first()
        return JsonResponse({"msg": "获取成功",
                             "data": {
                                 "isFriend": isFriend,
                                 "mail": user.mail,
                                 "password": user.password,
                                 "nickname": user.nickname,
                                 "iconUrl": user.iconUrl,
                                 "remark": remark,
                             }})
    else:
        return JsonResponse({"msg": "用户不存在"})
